<template>
  <div class="user">
    <el-row>
      <el-col :span="24">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>水质管理</el-breadcrumb-item>
          <el-breadcrumb-item>化验点位</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>

    <el-row :gutter="10">
      <el-col :span="2">
        <el-button type="success" plain icon="el-icon-plus" @click="showAddDialog1" size="mini"></el-button>
        <el-button type="danger" plain icon="el-icon-delete" @click="delete1" size="mini"></el-button>
      </el-col>    
      <el-col :span="10">
        <el-input placeholder="化验区域名称" class="search-input" v-model="query1" @keydown.native.enter="initList"  size="mini">
          <el-button slot="append" icon="el-icon-search" @click="initList"  size="mini" ></el-button>
        </el-input>
      </el-col>
      <el-col :span="2">
        <el-button type="danger" plain icon="el-icon-delete" @click="delete2" size="mini"></el-button>
      </el-col> 
    </el-row>

<el-row :gutter="10">
  <el-col :span="12">
    <!-- 列表1 -->
    <el-table ref="t1" class="margin-20" v-loading="loading" :data="list1" border style="width: 100%" highlight-current-row 
    row-key="ID" 
    @current-change="selectRow1" 
    @selection-change="val => this.multipleSelection1 = val">
    <el-table-column label="化验区域表">
      <el-table-column type="selection" width="50"></el-table-column>      
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column prop="AreaName" label="化验区域名称"></el-table-column>
      <el-table-column label="启停用"  width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.RecordEnable" @change="changeRecordEnable1(scope.row)"  :active-value= 1 :inactive-value= 0></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作"  width="200">
        <template slot-scope="scope">
            <el-button size="mini" type="primary" plain icon="el-icon-edit" @click="showEditDialog1(scope.row)"></el-button>
          <el-button size="mini" type="primary" plain icon="el-icon-arrow-right" @click="showAddDialog2(scope.row)"></el-button>
        </template>
      </el-table-column>
      </el-table-column>
    </el-table>
    <!-- <el-pagination
        @size-change="handleSizeChange1"
        @current-change="handleCurrentChange1"
        :current-page="1"
        :page-sizes="[10,20, 30, 40]"
        :page-size="10"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total1">
    </el-pagination> -->
    </el-col>
    <el-col :span="12">
      <!-- 列表2 -->
    <el-table class="margin-20" v-loading="loading" :data="list2" border style="width: 100%"
    row-key="ID" 
    @selection-change="val => this.multipleSelection2 = val">
    <el-table-column label="化验点位表">
      <el-table-column type="selection" width="50"></el-table-column>      
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column prop="PositionName" label="点位名称"></el-table-column>
      <el-table-column label="启停用"  width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.RecordEnable" @change="changeRecordEnable2(scope.row)"  :active-value= 1 :inactive-value= 0></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作"  width="200">
        <template slot-scope="scope">
            <el-button size="mini" type="primary" plain icon="el-icon-edit" @click="showEditDialog2(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table-column>
    </el-table>
    </el-col>
    </el-row>
     <!-- 添加区域对话框 -->
    <el-dialog :title="dialog1Title" :visible.sync="dialog1Visible" width="20%">
      <el-form :model="form1" label-position="right" label-width="110px" :rules="rules" ref="form1" size="medium" >
        <el-form-item label="化验区域名称" prop="AreaName">
          <el-input v-model="form1.AreaName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="启用" prop="RecordEnable">
          <el-switch v-model="form1.RecordEnable" :active-value= 1 :inactive-value= 0>
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog1Visible = false" size="medium">取 消</el-button>
        <el-button type="primary" @click="submit1()" size="medium">提 交</el-button>
      </div>
    </el-dialog>
    <!-- 添加点位对话框 -->
    <el-dialog :title="dialog2Title" :visible.sync="dialog2Visible" width="20%">
      <el-form :model="form2" label-position="right" label-width="110px" :rules="rules2" ref="form2" size="medium" >
        <el-form-item label="化验点位名称" prop="PositionName">
          <el-input v-model="form2.PositionName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="启用" prop="RecordEnable">
          <el-switch v-model="form2.RecordEnable" :active-value= 1 :inactive-value= 0>
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog2Visible = false" size="medium">取 消</el-button>
        <el-button type="primary" @click="submit2()" size="medium">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { existAreaName,existPositionName } from '@/api/wq-api'
import { apiGet, apiPost, apiPut, apiDelete } from '@/api/index'
import * as wqApi from '@/api/wq'
import * as uitools from '@/utils/utils'
import Sortable from 'sortablejs'

export default {
  data () {
    var validateAreaName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入区域名称'))
      }
      setTimeout(() => {
        apiGet(wqApi.existAreaName, { txt: value, id: this.id1 } ).then(res => {
        //existAreaName({ params: { txt: value, id: this.id1 } }).then(res => {
          if (res.code === 200) {
            if (res.data) {
              callback(new Error('区域名称已经存在'))
            } else {
              callback()
            }
          } else {
            callback(new Error('区域名称验证失败'))
          }
        })
      }, 500)
    }

    var validatePositionName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入点位名称'))
      }
      setTimeout(() => {
        apiGet(wqApi.existPositionName,  { txt: value, id: this.id2 } ).then(res => {
        //existPositionName({ params: { txt: value, id: this.id2 } }).then(res => {
          if (res.code === 200) {
            if (res.data) {
              callback(new Error('点位名称已经存在'))
            } else {
              callback()
            }
          } else {
            callback(new Error('点位名称验证失败'))
          }
        })
      }, 500)
    }

    return {
      aa:true,
      loading: true,
      id1:0,
      list1: [],
      query1: '',     
      pagesize1: 10,
      pagenum1: 1,
      total1: 0,
      multipleSelection1:[],

      id2:0,
      list2: [],
      query2: '',
      pagesize2: 10,
      pagenum2: 1,
      total2: 0,
      multipleSelection2:[],
      dialog1State:0,
      dialog1Visible:false,
      dialog1Title:'',      
      form1: {
        ID:0,
        AreaName: '',
        RecordEnable: 1
      },
      dialog2State:0,
      dialog2Visible:false,
      dialog2Title:'',  
      form2: {
        ID:0,
        PositionName: '',
        RecordEnable: 1
      },
      catch:{
        row:{}
      },
      rules: {
        AreaName: [
          //{ required: true, message: '请输入用户名', trigger: 'blur' }
          { required: true, validator: validateAreaName, trigger: 'blur' }
        ]
      },      
      rules2: {
        PositionName: [
          //{ required: true, message: '请输入用户名', trigger: 'blur' }
          { required: true, validator: validatePositionName, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.rowDrop()    
  },
  created () {
    this.initList()
  },
  methods: {
    rowDrop() {
      const tbodys = document.querySelectorAll('.el-table__body-wrapper tbody')
      const tbody1 = tbodys[0]
      const tbody2 = tbodys[1]
      //const tbody = document.querySelector('.el-table__body-wrapper tbody')

      const _this = this
      Sortable.create(tbody1, {
        onEnd({ newIndex, oldIndex }) {
          uitools.editNoValid(_this, wqApi.sortArea, {
            currentID:_this.list1[oldIndex].ID,
            targetID:_this.list1[newIndex].ID,
            currentSort:_this.list1[oldIndex].RecordSort,
            targetSort:_this.list1[newIndex].RecordSort
          }).then(res=>{
            _this.initList()
          })
          // console.log({ newIndex, oldIndex })
          // console.log(_this.list1[oldIndex].ID)
        }
      })
      Sortable.create(tbody2, {
        onEnd({ newIndex, oldIndex }) {
          uitools.editNoValid(_this, wqApi.sortPosition, {
            Aid:_this.catch.row.ID,
            currentID:_this.list2[oldIndex].ID,
            targetID:_this.list2[newIndex].ID,
            currentSort:_this.list2[oldIndex].RecordSort,
            targetSort:_this.list2[newIndex].RecordSort
          }).then(res=>{
            _this.initList()
            _this.$refs.t1.setCurrentRow(_this.catch.row)
          })
          // console.log({ newIndex, oldIndex })
          // console.log(_this.list1[oldIndex].ID)
        }
      })
    },
  selectRow1(currentRow, oldCurrentRow)
  {
     this.catch.row = currentRow
     uitools.selectRow(this.list1,this.list2=[],currentRow, oldCurrentRow)
  },
    handleSizeChange1 (val) {
      this.pagesize1 = val
      this.initList()
    },
    handleCurrentChange1 (val) {
      this.pagenum1 = val
      this.initList()
    },
    initList () {
      this.loading = true
      apiGet(wqApi.getAreaPosition, { AreaName: this.query1 } ).then(res => {
        this.list1 = res.data.rows
        this.total1 = res.data.total
        if(this.catch.row.ID){
          this.list2 = this.list1.find(obj=>obj.ID == this.catch.row.ID).Positions
          }else
        {
        this.list2 = []
        }
        this.loading = false
        console.log(this.list1)
        console.log(this.list2)
      })
      
    },
    showAddDialog1 () {
      this.id1 = 0
      this.dialog1Title = '添加化验区域'
      this.dialog1Visible = true
      this.resetForm('form1')
    },
    showEditDialog1 (row) {
      this.dialog1Title = '修改化验区域'
      this.dialog1Visible = true
      this.resetForm('form1')
      this.id1 = row.ID
      // this.form1.ID = row.ID
      // this.form1.AreaName = row.AreaName
      // this.form1.RecordEnable = row.RecordEnable
      //  this.form1 ={}
      this.$nextTick(() => this.form1 = Object.assign({},row))
      //this.form1 = Object.assign({},row)
      console.log(this.form1)

    },
    showAddDialog2 (row) {
      this.id1 = row.ID
      this.id2 = 0
      this.dialog2Title = `添加点位 -- ${row.AreaName}`
      this.dialog2Visible = true
      // this.form2.PositionName = ''
      // this.form2.RecordEnable = 1
      this.resetForm('form2')
    },
    showEditDialog2 (row) {
      this.dialog2Title = `修改点位 -- ${this.list1.find(obj=>obj.ID == row.Aid).AreaName}`
      this.dialog2Visible = true
      this.resetForm('form2')
      this.id2 = row.ID
      this.$nextTick(() => this.form2 = Object.assign({},row))
      //this.form2 = Object.assign({},row)
      // this.form2.aid = row.Aid 
      // this.form2.id = row.ID
      // this.form2.positionName = row.PositionName
      // this.form2.recordEnable = row.RecordEnable
    },
    submit1 () {
          if(this.id1 <= 0)
          {
            uitools.add(this, wqApi.addArea, this.form1, this.$refs['form1']).then(data=>{
                this.dialog1Visible = false
                this.initList()
            })
          }else{
            uitools.edit(this, wqApi.editArea, this.form1, this.$refs['form1']).then(data=>{
                this.dialog1Visible = false
                this.initList()
                //console.log(this.list1[0])
                this.$refs.t1.setCurrentRow(this.list1[0])
            })
          }
    },
    submit2 () {
          if(this.id2 <= 0)
          {
            this.form2.Aid = this.id1
            uitools.add(this, wqApi.addPosition, this.form2, this.$refs['form2']).then(data=>{
                this.dialog2Visible = false
                let obj = this.list1.find(obj=>obj.ID == this.id1)
                if(!obj.Positions)
                  obj.Positions = []
                obj.Positions.push(data)
                this.list2 = obj.Positions
            })
          }else{
            uitools.edit(this, wqApi.editPosition, this.form2, this.$refs['form2']).then(data=>{
                this.dialog2Visible = false
                let row = this.list2.find(obj=>obj.ID == this.form2.ID)
                row.PositionName = this.form2.PositionName
                row.RecordEnable = this.form2.RecordEnable
            })
          }
    },
    changeRecordEnable1 (row) {
        uitools.editNoValid(this, wqApi.editArea, row)
    },
    changeRecordEnable2 (row) {
        uitools.editNoValid(this, wqApi.editPosition, row)
    },
    delete1 (row) {
      uitools.deleteBatch(this, wqApi.deleteBatchArea, this.multipleSelection1)
      .then(data=>{ this.initList() })
    },
    delete2 (row) {
      uitools.deleteBatch(this, wqApi.deleteBatchPosition, this.multipleSelection2)
      .then(data=>{ 
        this.multipleSelection2.forEach((element,index,arr) => {
          let idx = this.list2.indexOf(this.list2.find(obj=>obj.ID == element.ID))
          this.list2.splice(idx,1)
          });
      })
    },
    resetForm (formName) {
      if (this.$refs[formName] != undefined){
        this.$nextTick(() => {this.$refs[formName].resetFields()});
      }

      // if (this.$refs[formName] !== undefined) {
      //   this.$refs[formName].resetFields()
      // }
    }
  }
}
</script>
<style lang="scss" scoped>
.user {
  .margin-20 {
    margin: 20px 0;
  }
  .search-input {
    // width: 300px;
  }
  .page {
    //padding: 5px 0;
    //background-color: #D3DCE6;
  }
}
</style>
